<?php

namespace app\api\controller;

use app\admin\model\shop\goods\Goods;
use app\admin\model\shop\Paidan;
use ba\Random;
use think\facade\Db;
use Throwable;
use ba\Captcha;
use think\Response;
use ba\ClickCaptcha;
use think\facade\Config;
use app\common\facade\Token;
use app\common\controller\Api;
use app\admin\library\Auth as AdminAuth;
use app\common\library\Auth as UserAuth;
use wxshop\ShopOrder;
use wxshop\ShopSharer;

class Common extends Api
{
    /**
     * 图形验证码
     * @throws Throwable
     */
    public function captcha(): Response
    {
        $captchaId = $this->request->request('id');
        $config = array(
            'codeSet' => '123456789',            // 验证码字符集合
            'fontSize' => 22,                     // 验证码字体大小(px)
            'useCurve' => false,                  // 是否画混淆曲线
            'useNoise' => true,                   // 是否添加杂点
            'length' => 4,                      // 验证码位数
            'bg' => array(255, 255, 255),   // 背景颜色
        );

        $captcha = new Captcha($config);
        return $captcha->entry($captchaId);
    }

    /**
     * 点选验证码
     */
    public function clickCaptcha(): void
    {
        $id = $this->request->request('id/s');
        $captcha = new ClickCaptcha();
        $this->success('', $captcha->creat($id));
    }

    /**
     * 点选验证码检查
     * @throws Throwable
     */
    public function checkClickCaptcha(): void
    {
        $id = $this->request->post('id/s');
        $info = $this->request->post('info/s');
        $unset = $this->request->post('unset/b', false);
        $captcha = new ClickCaptcha();
        if ($captcha->check($id, $info, $unset)) $this->success();
        $this->error();
    }

    public function refreshToken(): void
    {
        $refreshToken = $this->request->post('refreshToken');
        $refreshToken = Token::get($refreshToken);

        if (!$refreshToken || $refreshToken['expire_time'] < time()) {
            $this->error(__('Login expired, please login again.'));
        }

        $newToken = Random::uuid();

        // 管理员token刷新
        if ($refreshToken['type'] == AdminAuth::TOKEN_TYPE . '-refresh') {
            $baToken = get_auth_token();
            if (!$baToken) {
                $this->error(__('Invalid token'));
            }
            Token::delete($baToken);
            Token::set($newToken, AdminAuth::TOKEN_TYPE, $refreshToken['user_id'], (int)Config::get('buildadmin.admin_token_keep_time'));
        }

        // 会员token刷新
        if ($refreshToken['type'] == UserAuth::TOKEN_TYPE . '-refresh') {
            $baUserToken = get_auth_token(['ba', 'user', 'token']);
            if (!$baUserToken) {
                $this->error(__('Invalid token'));
            }
            Token::delete($baUserToken);
            Token::set($newToken, UserAuth::TOKEN_TYPE, $refreshToken['user_id'], (int)Config::get('buildadmin.user_token_keep_time'));
        }

        $this->success('', [
            'type' => $refreshToken['type'],
            'token' => $newToken
        ]);
    }

    public function setGoodsStatus()
    {
        $model = new Goods();
        $list = $model->select();
        if (isset($list)) {
            foreach ($list as $k => $v) {
                if ($v['status_up_time']) {
                    if ($v['status_up_time'] < time()) {
                        $v->status = 1;
                        $v->save();
                    }
                }
                if ($v['status_down_time']) {
                    if ($v['status_down_time'] < time()) {
                        $v->status = 0;
                        $v->save();
                    }
                }
            }
        }
        return $this->success('执行完成');
    }

    public function play_order()
    {
        $config = Db::name('shop_setting')->where('name', 'timeout')->value('value');

        if (isset($config) && $config != '') {
            $endtime = time() - ($config * 60);
            Db::name('shop_order_play')->where('status', 4)->where('update_time', '<=', $endtime)->update(['play_user_id' => 0, 'status' => 1, 'commission' => 0.00, 'update_time' => time()]);
        }
        return $this->success('执行完成');
    }

    public function StroeOrder()
    {
        $storelist = Db::name('store_store')->select();
        foreach ($storelist as $k => $v) {
            $stime = Db::name('store_order_log')->where(['store_id' => $v['id']])->order('id DESC')->value('create_time');
            if (!isset($stime) && $stime == '') {
                $stime = strtotime("-7 day");
            }
            if (isset($v['appid']) && $v['appid'] != '' && isset($v['secret']) && $v['secret'] != '') {
                $model = new ShopOrder($v['appid'], $v['secret']);
                $model->pullOrder($stime, $v['id']);
            }
        }
        return $this->success();
    }

    public function StroeSharer()
    {
        $storelist = Db::name('store_store')->select();
        foreach ($storelist as $k => $v) {
            if (isset($v['appid']) && $v['appid'] != '' && isset($v['secret']) && $v['secret'] != '') {
                $model = new ShopSharer($v['appid'], $v['secret']);
                $model->getSharer1($v['id']);
                $model->getSharer0($v['id']);
            }
        }
        return $this->success();
    }

    public function autolevel()
    {
        //达人
        $level_list1 = Db::name('shop_user')->where('level_id','null')->select();
        $config1 = Db::name('recommend_level')->where('radio',1)->value('num');
        if(isset($level_list1) && isset($config1) && $config1 != 0){
            foreach ($level_list1 as $k => $v) {
                $count = Db::name('store_order')->where('user_id',$v['id'])->count();
                if($count >= $config1){
                    Db::name('shop_user')->where('id',$v['id'])->update(['level_id'=>1]);
                    //奖励
                    $reward = Db::name('recommend_level')->where('radio',1)->value('reward');
                    $model = new Paidan();
                    $model->change($v['id'],4,$reward,$v['id']);
                }
            }
        }
        //切片师
        $level_list2 = Db::name('shop_user')->where('level_id',1)->select();
        $config2 = Db::name('recommend_level')->where('radio',2)->value('num');
        if(isset($level_list2) && isset($config2) && $config2 != 0){
            foreach ($level_list2 as $k => $v) {
                $count = Db::name('shop_user')->where('pid',$v['id'])->where('level_id',1)->count();
                if($count >= $config2){
                    Db::name('shop_user')->where('id',$v['id'])->update(['level_id'=>2]);
                    //奖励
                    $reward = Db::name('recommend_level')->where('radio',1)->value('reward');
                    $model = new Paidan();
                    $model->change($v['id'],4,$reward,$v['id']);
                }
            }
        }
        //选品师
        $level_list3 = Db::name('shop_user')->where('level_id',2)->select();
        $config3 = Db::name('recommend_level')->where('radio',3)->value('num');
        if(isset($level_list3) && isset($config3) && $config3 != 0){
            foreach ($level_list3 as $k => $v) {
                $countpid = self::GetLastUser($v['id'],[]);
                if(isset($countpid)){
                    $count = Db::name('shop_user')->where('id','in',$countpid)->where('level_id',2)->count();
                }else{
                    $count = 0;
                }
                if($count >= $config3 && count($countpid) > 30){
                    Db::name('shop_user')->where('id',$v['id'])->update(['level_id'=>3]);
                    //奖励
                    $reward = Db::name('recommend_level')->where('radio',1)->value('reward');
                    $model = new Paidan();
                    $model->change($v['id'],4,$reward,$v['id']);
                }
            }
        }
        //服务商
        $level_list4 = Db::name('shop_user')->where('level_id',3)->select();
        $config4 = Db::name('recommend_level')->where('radio',4)->value('num');
        if(isset($level_list4) && isset($config4) && $config4 != 0){
            foreach ($level_list4 as $k => $v) {
                $countpid = self::GetLastUser($v['id'],0);
                if(isset($countpid)){
                    $count = Db::name('shop_user')->where('id','in',$countpid)->where('level_id',3)->count();
                }else{
                    $count = 0;
                }
                if($count >= $config4 && count($countpid) > 100){
                    Db::name('shop_user')->where('id',$v['id'])->update(['level_id'=>4]);
                    //奖励
                    $reward = Db::name('recommend_level')->where('radio',1)->value('reward');
                    $model = new Paidan();
                    $model->change($v['id'],4,$reward,$v['id']);
                }
            }
        }
        return $this->success();
    }

    public function GetLastUser($pid = '', $list = [] ){
        //uid的直接下级
        $plist = Db::name('shop_user')->field('id,pid')->where('pid',$pid)->select();
        if(isset($plist)){
            foreach ($plist as $k => $v) {
                $list [] = $v['id'];
                if(isset($v['pid']) && $v['pid'] != ''){
                    $list += self::getLastUser($v['id'],$list);
                }
            }
        }
        return $list;
    }

    public function test()
    {
        $model = new \app\admin\model\shop\user\User();
        $res = $model->inviteAfter(7);
        dump($res);die();
    }
}